package com.ylbh.common.utils;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.resizers.configurations.ScalingMode;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;


public class TaoBaoUtils {
    private static Logger logger = LoggerFactory.getLogger("com.ylbh.common.utils.TaoBaoUtils");

    private static OSSClient ossClient = new OSSClient();

    private static Map<String, String> headers = new HashMap<>();
    {
        headers.put("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36");
    }

    /**
     * 上传文件
     * @param url
     * @return
     */
    public synchronized static String uploadFile(String url, String referer,String fileDir) {
        if (!StringUtils.isEmpty(referer))
            headers.put("Referer",referer);
        headers.put("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36");
        HttpResponse httpResponse;
        try {
            httpResponse = HttpUtils.doGet(url, headers);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("请求评论图片错误，url：{}，referer：{}",url,referer);
            return null;
        }

        HttpEntity entity = httpResponse.getEntity();
        InputStream inStream;
        try {
            inStream = entity.getContent();
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("获取评论图片二进制错误，url：{}，referer：{}",url,referer);
            return null;
        }

        byte[] bytes = input2byte(inStream);
        if(bytes == null){
            return null;
        }
        Image src=Toolkit.getDefaultToolkit().createImage(bytes);
        BufferedImage cutImage = toBufferedImage(src);

        //        压缩
        ByteArrayOutputStream byteArrayOutputStream = null;
        try {
            byteArrayOutputStream = new ByteArrayOutputStream();
            Thumbnails.of(cutImage).scale(1f).outputFormat("jpg").outputQuality(0.9).toOutputStream(byteArrayOutputStream);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("图片压缩失败：{}",url);
            return null;
        }

        InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        // 图片后缀
        String urlSuffix = url.substring(url.lastIndexOf("/") + 1);
        String date = DateHelper.getDate();
//        String ossUrl = ossClient.uploadFile2OSS(inStream, fileDir, urlSuffix, date);
        OSSClientUtil ossClientUtil = new OSSClientUtil();
        String ossUrl = ossClientUtil.uploadFile2OSS(inputStream, date+".jpg",fileDir);

        if(StringUtils.isBlank(ossUrl) || "fail".equals(ossUrl)){
            return null;
        }

        return fileDir + "/" + ossUrl;
    }

    public synchronized static String uploadFileGoods(String url, String referer,String fileDir) {
        headers.put("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36");
        HttpResponse httpResponse;
        try {
            httpResponse = HttpUtils.doGets(url, headers);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("请求评论图片错误，url：{}，referer：{}",url,referer);
            return null;
        }

        HttpEntity entity = httpResponse.getEntity();
        InputStream inStream;
        try {
            inStream = entity.getContent();
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("获取评论图片二进制错误，url：{}，referer：{}",url,referer);
            return null;
        }

        byte[] bytes = input2byte(inStream);
        if(bytes == null){
            return null;
        }
        Image src=Toolkit.getDefaultToolkit().createImage(bytes);
        BufferedImage cutImage = toBufferedImage(src);

        //        压缩
        ByteArrayOutputStream byteArrayOutputStream = null;
        try {
            byteArrayOutputStream = new ByteArrayOutputStream();
            Thumbnails.of(cutImage).scale(1f).outputFormat("jpg").outputQuality(0.9).toOutputStream(byteArrayOutputStream);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("图片压缩失败：{}",url);
            return null;
        }

        InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        // 图片后缀
        String urlSuffix = url.substring(url.lastIndexOf("/") + 1);
        String date = DateHelper.getDate();
//        String ossUrl = ossClient.uploadFile2OSS(inStream, fileDir, urlSuffix, date);
        OSSClientUtil ossClientUtil = new OSSClientUtil();
        String ossUrl = ossClientUtil.uploadFile2OSS(inputStream, date+".jpg",fileDir);

        if(StringUtils.isBlank(ossUrl) || "fail".equals(ossUrl)){
            return null;
        }

        return fileDir + "/" + ossUrl;
    }

    private static BufferedImage toBufferedImage(Image image) {
        if (image instanceof BufferedImage) {
            return (BufferedImage) image;
        }
        // This code ensures that all the pixels in the image are loaded
        image = new ImageIcon(image).getImage();
        BufferedImage bimage = null;
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();

        try {
            int transparency = Transparency.OPAQUE;
            GraphicsDevice gs = ge.getDefaultScreenDevice();
            GraphicsConfiguration gc = gs.getDefaultConfiguration();
            bimage = gc.createCompatibleImage(image.getWidth(null),
                    image.getHeight(null), transparency);
        } catch (HeadlessException e) {
        // The system does not have a screen
        }
        if (bimage == null) {
        // Create a buffered image using the default color model
            int type = BufferedImage.TYPE_INT_RGB;
            bimage = new BufferedImage(image.getWidth(null),
                    image.getHeight(null), type);
        }
        // Copy image to buffered image
        Graphics g = bimage.createGraphics();
        // Paint the image onto the buffered image
        g.drawImage(image, 0, 0, null);
        g.dispose();
        return bimage;

    }
    private static byte[] input2byte(InputStream inStream)   {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while (true) {
            try {
                if (!((rc = inStream.read(buff, 0, 100)) > 0)) {
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
            swapStream.write(buff, 0, rc);
        }
        return swapStream.toByteArray();
    }
}
